package com.ruoyi.binding.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.binding.domain.JDP.Params.*;
import com.ruoyi.binding.domain.JDP.Tools.HttpInfo;
import com.ruoyi.binding.domain.JDP.Tools.OkHttpSessionClient;
import com.ruoyi.binding.domain.MhOrderRawData;
import com.ruoyi.binding.service.IMhSecJDPService;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysDeptService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class MhSecJDPServiceImpl implements IMhSecJDPService {

    @Autowired
    private ISysDeptService deptService;

    private JSONObject safeResponseBody(Response response) throws IOException {
        if (response != null && response.isSuccessful()) {
            if (response.body() != null) {
                return JSON.parseObject(response.body().string());
            } else {
                return new JSONObject().fluentPut("code", 0).fluentPut("msg", "响应体为空");
            }
        } else {
            return new JSONObject().fluentPut("code", 0)
                    .fluentPut("msg", "请求失败，HTTP状态码：" + (response != null ? response.code() : "null"));
        }
    }

    /**
     * @param deptId
     * @param url
     * @param username
     * @param password
     * @return
     */
    @Override
    public int login(OkHttpSessionClient client, Long deptId, String url, String username, String password) throws Exception {
        client.setCurrentUser(String.valueOf(deptId), url);

        // 登录
        Response resp = client.postForm(client.getCurrentUser().getBaseUrl() + Login, Map.of(
                "acc", username,
                "pwd", password
        ));
        if (resp.body() != null) {
            String bodyStr = resp.body().string();
            JSONObject jsonResponse = JSONObject.parseObject(bodyStr);

            if (jsonResponse.getInteger(code) != 1) {
                throw new Exception("登录失败: " + jsonResponse.getString(msg));
            }
            log.info("用户 {} 登录成功, 响应: {}", username, bodyStr);
        } else {
            throw new Exception("登录失败: 响应体为空");
        }
        return 1; // 登录成功
    }

    /**
     * @param client
     * @return
     * @throws Exception
     */
    @Override
    public int login(OkHttpSessionClient client) throws Exception {
        SysDept dept = deptService.selectDeptById(SecurityUtils.getDeptId());
        if (dept == null) {
            throw new Exception("部门信息不存在");
        }
        String url = dept.getHttpUrl();
        String username = dept.getHttpUser();
        String password = dept.getHttpPwd();
        log.info("登录信息：URL={}, 用户名={}, 密码={}", url, username, password);
        return login(client, dept.getDeptId(), url, username, password);
    }

    /**
     * @param client
     * @return
     */
    @Override
    public JSONObject queryGameType(OkHttpSessionClient client) throws Exception {
        try {
            String url = client.getCurrentUser().getBaseUrl() + GetGameServerMangeList;
            Response response = client.get(url, Map.of());
            return safeResponseBody(response);
        } catch (Exception e) {
            log.error("查询游戏类型异常", e);
            return new JSONObject().fluentPut("code", 0).fluentPut("msg", "查询游戏类型异常：" + e.getMessage());
        }
    }

    /**
     * @param client
     * @return
     */
    @Override
    public JSONObject queryUserList(OkHttpSessionClient client) throws Exception {
        try {
            String url = client.getCurrentUser().getBaseUrl() + GetUserList;
            Response response = client.get(url, Map.of());
            return safeResponseBody(response);
        } catch (Exception e) {
            log.error("查询用户列表异常", e);
            return new JSONObject().fluentPut("code", 0).fluentPut("msg", "查询用户列表异常：" + e.getMessage());
        }
    }

    /**
     * @param client
     * @param param  抢单大厅订单查询参数
     * @return
     */
    @Override
    public JSONObject queryInsideRecOrder(OkHttpSessionClient client, JDPProOrderParam param) throws Exception {
        try {
            String url = client.getCurrentUser().getBaseUrl() + GetInsideRecOrderList;
            JSONArray allOrders = new JSONArray();
            //由于上家api限制 每次只能查询20条数据 且每次查询间隔不能小于2秒 所以需要分页查询
            int page = param.getPage();
            while (true) {
                Map<String, String> q = new HashMap<>();
                if (param.getGameName() != null) q.put("gameName", param.getGameName());
                q.put("page", String.valueOf(page));
                q.put("limit", String.valueOf(param.getLimit()));
                if (param.getKey() != null) q.put("key", param.getKey());
                if (param.getProject() != null) q.put("project", param.getProject());
                log.info("查询抢单大厅订单参数：{}", q);
                log.info("查询抢单大厅订单url：{}", url);
                Response response = client.get(url, q);
                JSONObject responseJson = safeResponseBody(response);

                JSONArray orders = responseJson.getJSONArray("data");
                if (orders == null || orders.isEmpty()) {
                    log.info("{} 第{}页 无订单，分页查询结束。", param.getGameName(), page);
                    break;
                }
                for (int i = 0; i < orders.size(); i++) {
                    allOrders.add(orders.getJSONObject(i));
                }
                log.info("{} 第{}页 获取 {} 条订单", param.getGameName(), page, orders.size());
                page++;
                Thread.sleep(2000); // 2秒间隔
            }
            log.info("所有游戏订单总数：{}", allOrders.size());
            return new JSONObject().fluentPut("code", 1)
                    .fluentPut("msg", "查询成功")
                    .fluentPut("total", allOrders.size())
                    .fluentPut("data", allOrders);
        } catch (Exception e) {
            log.error("抢单大厅订单查询异常", e);
            return new JSONObject().fluentPut("code", 0).fluentPut("msg", "抢单大厅订单查询异常：" + e.getMessage());
        }
    }

    /**
     * @param client
     * @param param 抢单大厅抢单参数
     * @return
     */
    @Override
    public JSONObject takeOrder(OkHttpSessionClient client, JDPProTakeOrderParam param) throws Exception {
        try {
            String url = client.getCurrentUser().getBaseUrl() + RecOrderSliderVerifiCode;
            Map<String, String> formData = Map.of("id", param.getId());
            Response response = client.postForm(url, formData);
            return safeResponseBody(response);
        } catch (Exception e) {
            log.error("抢单异常", e);
            return new JSONObject().fluentPut("code", 0).fluentPut("msg", "抢单异常：" + e.getMessage());
        }
    }

    /**
     * @param client
     * @param param  订单管理查询参数
     * @return
     */
    @Override
    public JSONObject queryOrder(OkHttpSessionClient client, JDPCusQueryOrderParam param) {
        try {
            String url = client.getCurrentUser().getBaseUrl() + GetOrderList;
            Map<String, String> q = new HashMap<>();
            if (param.getGameName() != null) q.put("gameName", param.getGameName());
            if (param.getKey1() != null) q.put("Key1", param.getKey1());
            q.put("page", String.valueOf(param.getPage()));
            q.put("limit", String.valueOf(param.getLimit()));
            log.info("查询参数{}", q);
            Response response = client.postForm(url, q);
            return safeResponseBody(response);
        } catch (Exception e) {
            log.error("订单查询异常", e);
            return new JSONObject().fluentPut("code", 0).fluentPut("msg", "订单查询异常：" + e.getMessage());
        }
    }

    /**
     * @param client
     * @return
     * @throws Exception
     */
    @Override
    public MhOrderRawData queryAllOrder(OkHttpSessionClient client) throws Exception {
        return null;
    }

    /**
     * @param client
     * @param param  订单指派参数
     * @return
     */
    @Override
    public JSONObject allocate(OkHttpSessionClient client, JDPCusAllocateParam param) throws Exception {
        try {
            String url = client.getCurrentUser().getBaseUrl() + SetOrderZhiPaiByIDX;
            Map<String, String> formData = new HashMap<>();
            formData.put("orderId", param.getOrderId());
            String strParameterJson = JSON.toJSONString(param.getStrParameter());
            formData.put("strParameter", strParameterJson);
            formData.put("isAutoAss", param.getIsAutoAss());
            formData.put("isOpenThrowOrderPricePerce", param.getIsOpenThrowOrderPricePerce());
            formData.put("taskNeedJobId", param.getTaskNeedJobId());
            Response response = client.postForm(url, formData);
//            打印参数
            log.info("订单指派参数：{}", formData);

            return safeResponseBody(response);
        } catch (Exception e) {
            log.error("订单指派异常", e);
            return new JSONObject().fluentPut("code", 0).fluentPut("msg", "订单指派异常：" + e.getMessage());
        }
    }

    /**
     * @param client
     * @param param  机位/打手设置参数
     * @return
     */
    @Override
    public JSONObject setUser(OkHttpSessionClient client, JDPCusSetUserParam param) throws Exception {
        try {
            String url = client.getCurrentUser().getBaseUrl() + SetOrderJiWei;
            Map<String, String> formData = Map.of(
                    "orderId", param.getOrderId(),
                    "jiwei", param.getJiwei()
            );
            Response response = client.postForm(url, formData);
            return safeResponseBody(response);
        } catch (Exception e) {
            log.error("机位设置异常", e);
            return new JSONObject().fluentPut("code", 0).fluentPut("msg", "机位设置异常：" + e.getMessage());
        }
    }

    /**
     * @param client
     * @param param
     * @return
     */
    @Override
    public JSONObject updateOrderStatus(OkHttpSessionClient client, JDPSetOrderStaParam param) throws Exception {
        try {

            String url = client.getCurrentUser().getBaseUrl() + UpdateOrderStatus;
            Map<String, String> formData = Map.of(
                    "orderId", param.getOrderId(),
                    "sta", param.getSta(),
                    "changeSoureType", param.getChangeSoureType(),
                    "isSyncTaoBao", param.getIsSyncTaoBao()
            );
            Response response = client.postForm(url, formData);
            return safeResponseBody(response);
        } catch (IOException e) {
            log.error("修改订单状态异常", e);
            return new JSONObject().fluentPut("code", 0).fluentPut("msg", "修改订单状态异常：" + e.getMessage());
        }
    }


}
